package com.fulihui.wgj.service.system;

import com.alibaba.dubbo.config.annotation.Service;
import com.fulihui.common.builder.rpc.RpcResultBuilder;
import com.fulihui.common.constants.ComponentConstants;
import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.enums.WxSystemConfigKeyEnum;
import com.fulihui.common.error.Errors;
import com.fulihui.common.error.InvokeServiceException;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.util.ConditionValidator;
import com.fulihui.common.util.JedisUtil;
import com.fulihui.wgj.dal.mybatis.domain.WxSystemConfig;
import com.fulihui.wgj.dal.mybatis.mapper.WxSystemConfigMapper;
import com.fulihui.wgj.facade.dto.WxSystemConfigDTO;
import com.fulihui.wgj.facade.request.system.WxSystemConfigRequest;
import com.fulihui.wgj.facade.result.system.WxSystemConfigResult;
import com.fulihui.wgj.facade.service.system.WxSystemCongfigService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author wang_wx
 * @date 2018-06-20
 */
@Component
@Service(interfaceClass = WxSystemCongfigService.class, version = "1.0.0")
public class WxSystemConfigServiceImpl implements WxSystemCongfigService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxSystemConfigServiceImpl.class);

    @Resource
    WxSystemConfigMapper wxSystemConfigMapper;

    @Autowired
    JedisUtil jedisUtil;

    @Override
    public BaseResult refreshConfig(WxSystemConfigRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        // 校验数据库是否已经有过该code的信息
        WxSystemConfig wxSystemConfig = BeanConv.copy(request, WxSystemConfig.class);
        List<WxSystemConfig> wxSystemConfigs = queryByExample(wxSystemConfig);
        int count;
        if (CollectionUtils.isEmpty(wxSystemConfigs)) {
            count = wxSystemConfigMapper.insertSelective(wxSystemConfig);
        } else {
            wxSystemConfig.setGmtModified(new Date());
            count = wxSystemConfigMapper.updateByExampleSelective(wxSystemConfig, buildUpdateExample(wxSystemConfig));
        }
        LOGGER.info("rpc WxSystemCongfigService refreshConfig count = {}", count);
        try {
            if (WxSystemConfigKeyEnum.component_access_token.equals(request.getCode())) {
                // 将第三方开放平台存进redis中供其他项目组使用
                jedisUtil.set(ComponentConstants.COMPONENT_ACCESS_TOKEN_KEY, request.getDescript(), 604800);
                LOGGER.info("第三方平台token存进redis中成功，component_access_token={}", request.getDescript());
            }
        } catch (Exception e) {
            LOGGER.error("第三方平台token存进redis异常{}", e.getMessage(), e);
        }
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.WxSystemConfigError.REFRESH_FAILED);
    }

    @Override
    public WxSystemConfigResult findConfigByCode(String code) {
        if (StringUtils.isBlank(code)) {
            return RpcResultBuilder.fail(WxSystemConfigResult.class, Errors.Commons.RECORD_NOT_EXISTS);
        }
        Example example = new Example(WxSystemConfig.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("code", code);
        WxSystemConfig wxSystemConfig = wxSystemConfigMapper.selectOneByExample(example);
        WxSystemConfigResult result = RpcResultBuilder.succ(WxSystemConfigResult.class);
        if (Objects.nonNull(wxSystemConfig)) {
            WxSystemConfigDTO wxSystemConfigDTO = BeanConv.copy(wxSystemConfig, WxSystemConfigDTO.class);
            result.setValue(wxSystemConfigDTO);
        }
        return result;
    }

    /**
     * 动态查询
     *
     * @param wxSystemConfig
     * @return
     */
    List<WxSystemConfig> queryByExample(WxSystemConfig wxSystemConfig) {
        if (Objects.isNull(wxSystemConfig)) {
            return wxSystemConfigMapper.selectAll();
        }
        Example example = new Example(WxSystemConfig.class);
        Example.Criteria criteria = example.createCriteria();
        String code = wxSystemConfig.getCode();
//        String descript = wxSystemConfig.getDescript();
        if (StringUtils.isNotBlank(code)) {
            criteria.andEqualTo("code", code);
        }
        //FIXME 查询条件暂时只传code
//        if (StringUtils.isNotBlank(descript)) {
//            criteria.andEqualTo("descript", descript);
//        }
        List<WxSystemConfig> wxSystemConfigs = wxSystemConfigMapper.selectByExample(example);
        return wxSystemConfigs;
    }

    /**
     * 组织更新的Example
     *
     * @param wxSystemConfig
     * @return
     */
    Example buildUpdateExample(WxSystemConfig wxSystemConfig) {
        Example example = new Example(WxSystemConfig.class);
        Example.Criteria criteria = example.createCriteria();
        String code = wxSystemConfig.getCode();
        if (StringUtils.isNotBlank(code)) {
            criteria.andEqualTo("code", code);
        }
        return example;
    }
}
